
import { DICT_TYPE, getIntDictOptions } from "@/utils/dict";
import { Col, Form, Input, Modal, Row, Select, InputNumber, theme, Radio, Spin, TreeSelect, message, Tag } from "antd";
import React, { useState, useEffect, useRef, useImperativeHandle, } from "react";
import TextArea from "antd/es/input/TextArea";
import { propertyApi, classApi } from "@/api";

/**@description 产品管理-行业类目属性-属性配置表单 */
const PropertyForm = ({ onRef, getList = Function }) => {
    const [disabled, setDisabled] = useState(false);
    const [treeData, setTreeData] = useState([]);
    const [show, setShow] = useState(false);
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();

    /**@description 加载行业树 */
    const loadClassTree = async () => {
        const data = await classApi.getClassList();
        setTreeData(data?.list ? data.list[0].children : [])
    }


    /**@description 表单布局 */
    const formItemLayout = {
        labelCol: {
            xs: {
                span: 24,
            },
            sm: {
                span: 4,
            },
        },
        wrapperCol: {
            xs: {
                span: 24,
            },
            sm: {
                span: 20,
            },
        },
    };

    /**@description 取消 */
    const onCanle = () => {
        setShow(false);
        setDisabled(false);
    }

    /**@description 添加|修改操作 */
    const open = async ({
        type = String || undefined,
        record = {},
    }) => {
        const { id = undefined } = record;
        setShow(true);
        form.resetFields();
        form.setFieldValue("type", "action." + type)

        console.log("添加", type, record)


        if (type === "update") {
            if (id) {
                setDisabled(true);
                try {
                    setLoading(true);
                    const data = await propertyApi.getProperty(id);
                    console.log("编辑，详情", data)
                    const { classId, className, propertyName, propertyValue, sort, status } = data;
                    form.setFieldsValue({
                        id,
                        className,
                        classId,
                        propertyName,
                        sort,
                        status,
                        classSelectValue: classId
                    });
                    if (propertyValue) {
                        //数组
                        form.setFieldValue("propertyValue", (JSON.parse(propertyValue)).join("\n"))
                    }

                } catch (error) {
                    Modal.error({
                        title: "错误",
                        content: error
                    })
                } finally {
                    setLoading(false);
                }
            }
        } else if (type === "add") {
            // // 新增 
            // form.setFieldValue("parentId", id);
            form.setFieldsValue({
                "parentId": id,
                propertyType: "1"
            })
        } else {
            form.setFieldValue("parentId", "0");
        }


    }

    /**@description 异步保存数据 */
    const createForm = async (value) => {

        try {
            const { propertyValue } = value;
            const params = {
                ...value,
                propertyValue: propertyValue ? propertyValue.split("\n") : [],
            }
            const data = await propertyApi.createProperty(params);
            getList();
            onCanle();
        } catch (error) {

        } finally {

        }

    }

    /**@description 校验表单 */
    const validateForm = async () => {
        try {
            const values = await form.validateFields();
            console.log("校验成功", values)
            createForm(values)
        } catch (error) {
            console.log("校验失败")
        }
    }

    /**@description 向外暴露方法 */
    useImperativeHandle(onRef, () => ({
        open
    }))



    useEffect(() => {
        show && loadClassTree();
        !show && form.resetFields()
    }, [show])

    const formProps = {
        form,
        rules: {
            propertyName: [{ required: true, message: '必须输入属性名称' }],
            classId: [{ required: true, message: '必须选择行业类目' }],
            status: [{ required: true, message: '状态选项为必选项' }],
        }
    }

    return (
        <>
            <Modal
                title="属性编辑"
                width={550}
                open={show}
                centered={true}
                destroyOnClose={true}
                onCancel={onCanle}
                onOk={validateForm}
            >
                <Spin spinning={loading}>
                    <Form
                        {...formItemLayout}
                        {...formProps}
                    >
                        <Row gutter={24}>
                            <Col span={24} style={{ display: "none" }} >
                                <Form.Item label="id" name="id">
                                    <Input />
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item
                                    rules={formProps.rules["propertyName"]}
                                    label="属性名称" name="propertyName">
                                    <Input placeholder="请输入属性名称，例如：颜色" />
                                </Form.Item>
                            </Col>
                            <Col span={24} style={{ display: "none" }}>
                                <Form.Item label="classId" name="classId"><Input /></Form.Item>
                            </Col>
                            <Col span={24} style={{ display: "none" }}>
                                <Form.Item label="className" name="className"><Input /></Form.Item>
                            </Col>
                            <Col span={24}>

                                <Form.Item
                                    rules={formProps.rules["classId"]}
                                    label="行业类目" name="classSelectValue">
                                    <TreeSelect
                                        disabled={disabled}
                                        treeData={treeData}
                                        onChange={({ label, value }, options) => {
                                            form.setFieldsValue({
                                                classId: value,
                                                className: label
                                            })
                                        }}
                                        labelInValue
                                        fieldNames={{
                                            label: "className",
                                            value: "id"
                                        }}
                                    />

                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="显示排序" name="sort">
                                    <InputNumber />
                                </Form.Item>
                            </Col>

                            <Col span={24}>
                                <Form.Item
                                    rules={formProps.rules["status"]}
                                    label="属性状态" name="status">
                                    <Radio.Group
                                        options={getIntDictOptions(DICT_TYPE.COMMON_STATUS)}
                                        optionType="button"
                                        buttonStyle="solid"
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="属性值" name="propertyValue" tooltip="每输入完一个属性值后按回车换行进行下一个输入">
                                    <TextArea rows={4} placeholder="每个属性独占一行，输入完后按回车键换行，例如：红色" />
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Spin>

            </Modal>
        </>
    )
}


export default PropertyForm;